var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    files:[],
    orderId: 0,
    orderInfo: {},
    posters:'',
    orderGoods: [],
    index:0,
    openAttr:false,
    choiceText:'请选择原因',
    array:[],
    reasonIds:[],
    remark:'',
    noteMaxLen:200,
    currentNoteLen:0
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数 
    this.setData({
      orderId: options.id
    });
    this.getOrderDetail();
    this.getReson();
  },
    onPullDownRefresh: function () {
        this.getOrderDetail();
    },
    getReson(){
      let _this = this;
      util.request(api.orderUrl.commodifyOrderReason).then(res=>{
        _this.setData({
          array:res.result
        })

      }).catch(err=>{
        console.log(err)
      })
    },
  getOrderDetail() {
    let that = this;
    util.request(api.orderUrl.orderDetail, {
      orderId: that.data.orderId
    }).then(function (res) {
      if (res.code == 200) {
        that.setData({
          orderGoods: res.result,
        });
      }
    });
  },
  makePhone() {
    let phone = this.data.orderInfo.leaderPhone;
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function(res) {
        console.log(res)
      }
    })
  },
  payTimer() {
    let that = this;
    let orderInfo = that.data.orderInfo;

    setInterval(() => {
      console.log(orderInfo);
      orderInfo.add_time -= 1;
      that.setData({
        orderInfo: orderInfo,
      });
    }, 1000);
  },
  _input(event) {
      let value = event.detail.value,
          len = parseInt(value.length)
      this.setData({
          currentNoteLen: len,
          remark: value
      })
  },
  payOrder() {
    let that = this;
    util.request(api.PayPrepayId, {
      orderId: that.data.orderId
    }).then(function (res) {
      if (res.errno === 0) {
        const payParam = res.data;
        wx.requestPayment({
          'timeStamp': payParam.timeStamp,
          'nonceStr': payParam.nonceStr,
          'package': payParam.package,
          'signType': payParam.signType,
          'paySign': payParam.paySign,
          'success': function (res) {
            console.log(res)
          },
          'fail': function (res) {
            console.log(res)
          }
        });
      }
    });

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  selectFile(files) {
    console.log('files', files)
    // 返回false可以阻止某次文件上传
  },
  uplaodFile(files) {
    console.log('upload files===========', files)
    // 文件上传的函数，返回一个promise
    return new Promise((resolve, reject) => {
      console.log(resolve);
      console.log(reject);
      let obj = {
        url: files.tempFilePaths[0]
      }
      wx.showLoading({
        title: "正在上传中"
    })
    

      this.setData({
        files: this.data.files.concat(obj),
        [`formData.selectFile`]: this.data.files.concat(obj)
      });
      console.log(this.data.files);
    })
  },
  uploadError(e) {
    console.log('upload error', e.detail)
  },
  uploadSuccess(e) {
    console.log('upload success', e.detail)
  },
  chooseImage(e){
    console.log(e)
    let _this = this;

    wx.uploadFile({
      url: api.leader.uploadImageUrl, 
      filePath: e.detail.tempFilePaths[0],
      name: 'file',
      success (result){
          wx.hideLoading();
          if(result.statusCode === 413){
              return wx.showToast({
                  title: "图片太大了",
                  icon: "error"
              })
          }
          let files = _this.data.files;
          result.data = JSON.parse(result.data);
          const data = result.data.message;
          let posters = _this.data.posters;
          if(posters==''){
            posters+=data;
          }else{
            posters+=',';
            posters+=data;
          }
          files.push({
            url:data
          });
          _this.setData({
            files:files,
            posters:posters
          })
      }
  })
  },
  bindPickerChange(e){
    console.log(e);
    let _this = this;
    this.setData({
      choiceText:_this.data.array[parseInt(e.detail.value)].reasonDesc
    })
    console.log(1113,e)
  },
  choiceItem(e) {
    let arrayData = this.data.array;
    let arrayItem = this.data.array.find(res=>res.reasonId == e.currentTarget.dataset.itemId);
    let arrayIndex = this.data.array.findIndex(res=>res.reasonId == e.currentTarget.dataset.itemId);
    if(arrayItem.active){
      arrayData[arrayIndex].active = false;
    }else{
      arrayData[arrayIndex].active = true;
    }
    let reasonIds = [];
    let choiceText = '';
    for(let i=0;i<arrayData.length;i++){
      if(arrayData[i].active){
        reasonIds.push(arrayData[i].reasonId);
        if(choiceText==''){
          choiceText+=arrayData[i].reasonDesc;
        }else{
          choiceText+=',';
          choiceText+=arrayData[i].reasonDesc;
        }
      }
    }
    this.setData({
      array:arrayData,
      reasonIds:reasonIds,
      
    })

    if(choiceText==''){
      this.setData({
        choiceText:'请选择原因'
      })
    }else{
      this.setData({
        choiceText:choiceText
      })
    }
  },
  //隐藏对话框
  hideModal: function() {
      // 隐藏遮罩层
      var animation = wx.createAnimation({
          duration: 200,
          timingFunction: "linear",
          delay: 0
      })
      this.animation = animation
      animation.translateY(300).step()
      this.setData({
          animationData: animation.export(),
      })
      setTimeout(function() {
          animation.translateY(0).step()
          this.setData({
              animationData: animation.export(),
              openAttr: false,
          })
      }.bind(this), 200)
  },
  submitForm() {
    let _this = this;
    if(_this.data.posters==''){

      wx.showToast({
        title:'请上传凭证图片'
      })
      return
    }
    if(_this.data.reasonIds.length==0){

      wx.showToast({
        title:'请选择原因'
      })
      return
    }

    if(_this.data.remark==''){

      wx.showToast({
        title:'请输入问题描述'
      })
      return
    }
    util.request(api.commodityOrderApply,{
      orderId:_this.data.orderId,
      posters:_this.data.posters,
      reasonIds:_this.data.reasonIds,
      remark:_this.data.remark,
    },'POST').then(res=>{
      wx.showToast({
        title: "退款申请提交成功"
      })
      wx.navigateBack();
    }).catch(err=>{
      wx.showToast({
        title: "退款申请失败"
      })
      console.log(err)
    })
  },
  //显示对话框
  showModal: function() {
      // 显示遮罩层
      var animation = wx.createAnimation({
          duration: 200,
          timingFunction: "linear",
          delay: 0
      })
      this.animation = animation
      animation.translateY(300).step()
      this.setData({
          animationData: animation.export(),
          openAttr: true
      })
      setTimeout(function() {
          animation.translateY(0).step()
          this.setData({
              animationData: animation.export()
          })
      }.bind(this), 200)
  },

})